<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ArrowRight } from '@element-plus/icons-vue';
import { Project } from '@/components/projects/Project';
import type { ProjectInfo } from '@/types/ProjectInfo';
import { ElMessage } from 'element-plus';
import { onMounted } from 'vue';
import { sleepAsync } from '@/utils/test-api';
import { Part } from '@/types/Part';
import { getPartsAsync } from '@/utils/project-api';
import type { PartDetails } from '@/types/PartDetails';
import { PartStatus } from '@/types/Part';

// 定义组件的名称，用来做页面缓存
defineOptions({ name: 'mixing-process' });

const project = new Project();
const projects = ref<ProjectInfo[]>([]);
const tableData = ref<any[]>([]); //页面展示数据
const projectId = ref<string>(''); //选择的项目ID
const router = useRouter(); //路由
const pageIndex = ref(0);
const pageSize = 50;

const loadingText = ref('正在加载页面...');
const isLoading = ref(false);

function openLoading() {
  isLoading.value = true;
}

function closeLoading() {
  isLoading.value = false;
}

// 更新项目列表
async function updateProjectsAsync() {
  loadingText.value = '正在加载项目列表...';
  try {
    openLoading();
    projects.value = await project.getAsync(pageIndex.value * pageSize, pageSize);
  } catch (err) {
    const message = err as string;
    if (message != null) {
      ElMessage.warning(message);
    } else {
      console.error(err);
      ElMessage.error('获取项目列表错误！');
    }
  } finally {
    closeLoading();
  }
}

// 更新部件列表
async function updatePartsAsync() {
  loadingText.value = '正在加载部件...';
  openLoading();
  try {
    await sleepAsync(500);
    const result = await getPartsAsync(projectId.value);
    if (result.isSuccess) {
      filterMixingParts(result.result ?? []);
      filterpulpingMachineParts(result.result ?? []);
    } else {
      throw result.message;
    }
  } catch (err) {
    const message = err as string;
    if (message != null) {
      ElMessage.warning(message);
    } else {
      console.error(err);
      ElMessage.error('获取部件列表错误！');
    }
  } finally {
    closeLoading();
  }
}

onMounted(async () => {
  await updateProjectsAsync();
});

// 搅拌
const mixingTankDetails = ref<PartDetails>({
  categoryName: '搅拌车间-搅拌机',
  totalCount: '--',
  runingCount: '--',
  stopCount: '--',
  warningCount: '--'
});

// 过滤阳极&阴极搅拌机
function filterMixingParts(parts: Part[]) {
  const topParts = parts.filter((item) => item.partOwnerId == null);
  const regex = /^[0-9]{1,3}#(阳极|阴极)搅拌机-[\w]{1,}$/;
  const totalParts = topParts.filter((item) => regex.test(item.partName));
  mixingTankDetails.value.totalCount = totalParts.length.toString();
  mixingTankDetails.value.runingCount = totalParts
    .filter((item) => item.partStatus == PartStatus.None)
    .length.toString();
  mixingTankDetails.value.stopCount = totalParts
    .filter((item) => item.partStatus == PartStatus.RequireMaintenance)
    .length.toString();
  mixingTankDetails.value.warningCount = totalParts
    .filter((item) => item.partStatus == PartStatus.Warning)
    .length.toString();
}

// 制浆
const pulpingMachineDetails = ref<PartDetails>({
  categoryName: '搅拌车间-制浆机',
  totalCount: '--',
  runingCount: '--',
  stopCount: '--',
  warningCount: '--'
});

// 过滤阳极&阴极搅拌机
function filterpulpingMachineParts(parts: Part[]) {
  const topParts = parts.filter((item) => item.partOwnerId == null);
  const regex = /^[0-9]{1,3}#(阳极|阴极)制浆机-[\w]{1,}$/;
  const totalParts = topParts.filter((item) => regex.test(item.partName));
  pulpingMachineDetails.value.totalCount = totalParts.length.toString();
  pulpingMachineDetails.value.runingCount = totalParts
    .filter((item) => item.partStatus == PartStatus.None)
    .length.toString();
  pulpingMachineDetails.value.stopCount = totalParts
    .filter((item) => item.partStatus == PartStatus.RequireMaintenance)
    .length.toString();
  pulpingMachineDetails.value.warningCount = totalParts
    .filter((item) => item.partStatus == PartStatus.Warning)
    .length.toString();
}

// 粉料
const powderDetails = ref<PartDetails>({
  categoryName: '粉料车间-粉料',
  totalCount: '--',
  runingCount: '--',
  stopCount: '--',
  warningCount: '--'
});

// 溶剂
const solventDetails = ref<PartDetails>({
  categoryName: '搅拌车间-溶剂',
  totalCount: '--',
  runingCount: '--',
  stopCount: '--',
  warningCount: '--'
});

// 溶剂
const slurryDetails = ref<PartDetails>({
  categoryName: '搅拌车间-浆料',
  totalCount: '--',
  runingCount: '--',
  stopCount: '--',
  warningCount: '--'
});

// 初始化数据
tableData.value = [
  mixingTankDetails.value,
  pulpingMachineDetails.value,
  powderDetails.value,
  solventDetails.value,
  slurryDetails.value
];

// 监听项目名称改变
const projectChange = (e: string) => {
  if (e != null || e != '') {
    updatePartsAsync();
  }
};

// 跳转至总览页面
const clickOpen = () => {
  if (!projectId.value) return ElMessage.warning('请先选择项目!');
  router.push({
    path: '/mixing-process/mixing-pulping',
    query: { projectId: projectId.value }
  });
};
</script>

<template>
  <div class="main-container" v-loading="isLoading" :element-loading-text="loadingText">
    <div class="main">
      <div class="top-form">
        <span>项目名称：</span>
        <el-select class="select-project" @change="projectChange" v-model="projectId">
          <el-option
            v-for="item in projects"
            :key="item.id"
            :label="item.projectName"
            :value="item.id"
          />
        </el-select>
      </div>
      <div class="main-title">前工序-搅拌工序设备</div>
      <div class="content">
        <div class="main-container-content" v-for="(item, index) in tableData" :key="item + index">
          <div class="title">{{ item.categoryName }}</div>
          <div class="details">
            <div class="detail-item">
              <div class="label">总数：</div>
              <div class="value">{{ item.totalCount }}</div>
            </div>
            <div class="detail-item">
              <div class="label">当前运行：</div>
              <div class="value">{{ item.runingCount }}</div>
            </div>
            <div class="detail-item">
              <div class="label">当前停机：</div>
              <div class="value">{{ item.stopCount }}</div>
            </div>
            <div class="detail-item">
              <div class="label">当前报警：</div>
              <div class="value">{{ item.warningCount }}</div>
            </div>
            <div class="foot-icon" v-if="[0, 1].includes(index)" @click="clickOpen">
              <div>
                <el-icon>
                  <arrow-right />
                </el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
$pageFontSize: 30px;
$background-color: transparent;
$border-color: #446e9a;
$font-color: rgb(221.7, 222.6, 224.4);
$hover-color: #409eff;

.main-container {
  height: 100%;
  overflow: hidden;
  width: 100%;
  background-image: url('@/assets/img/xingkong.png');
  /* 可选的背景属性 */
  background-size: 100% 100%;
  background-position: center; /* 图片居中 */
  background-repeat: no-repeat; /* 图片不重复 */

  .top-form {
    color: $font-color;
    display: flex;
    align-items: center;
    .select-project {
      width: 240px;
      :deep(.el-select__wrapper) {
        background: $background-color;
        box-shadow: 0 0 0 1px $border-color inset;
        &:hover {
          box-shadow: 0 0 0 1px rgb(51.2, 126.4, 204) inset;
        }
        &:active {
          outline: unset;
          box-shadow: 0 0 0 1px var(--el-color-primary) inset;
        }
      }
      :deep(.el-select__placeholder) {
        color: $font-color;
      }
    }
  }

  .main {
    // background-color: #100b30;
    padding: 20px;
    height: 100%;

    .main-title {
      position: absolute;
      font-size: 45px;
      font-family: 'Courier New', Courier, monospace;
      font-weight: bold;
      color: $font-color;
      left: 50%;
      transform: translateX(-50%);
      user-select: none;
    }

    .content {
      display: flex;
      align-items: center;
      justify-content: space-around;
      height: 100%;
      width: 100%;
    }

    .main-container-content {
      font-size: $pageFontSize;
      width: 16%;
      height: 80%;
      color: $font-color;
      border-radius: 10px;
      border-width: 2px;
      border-color: $border-color;
      border-style: solid;
      text-align: center;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      /* 添加过渡效果 */
      .title {
        font-family: 'Courier New', Courier, monospace;
        margin-bottom: 10px;
        user-select: none;
      }

      .details {
        font-family: 'Courier New', Courier, monospace;
        position: relative;

        .detail-item {
          display: flex;
          margin-bottom: 10px;
          user-select: none;
        }

        .foot-icon {
          position: absolute;
          top: calc(100% + 50px);
          left: calc(50% - 25px);
          height: 50px;
          cursor: pointer;

          div {
            width: 50px;
            height: 50px;
            line-height: 57px;
            border-radius: 50%;
            background: $border-color;
            transition: background 0.3s, color 0.3s;
            /* 添加过渡效果 */
            display: flex;
            justify-content: center;
            align-items: center;
          }

          div:hover {
            background-color: $hover-color;
            color: #fff;
          }
        }
      }
    }

    .main-container-content:hover {
      box-shadow: 0 0px 12px $hover-color;
      /* 鼠标移入时的阴影效果 */
    }
  }
}
</style>
